import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import {routers} from './router';
import Util from '@/libs/util';
import Cookies from 'js-cookie';
import store from '@/store';
import appRouter from '../router/appRouter';

Vue.use(VueRouter);

// 路由配置
const RouterConfig = {
    mode: 'history',
    routes: routers
};

export const router = new VueRouter(RouterConfig);

//1.请求用户权限
const requestPermission = params => {
    return Util.axios.post('/ms/getPermission', {}, {withCredentials: true});
};

//2.获取路由信息
const getRoutes = userInfo => {
    if (!userInfo.menus) {
        return console.warn(userInfo);
    }
    //转成hash
    let hashMenus = {};
    let setMenu2Hash = function (array, base) {
        array.map(key => {
            if (key.menuurl) {
                let hashKey = ((base ? base : '') + key.menuurl).replace(/^\//, '');
                let obj = {icon: key.icon, title: key.menuname};
                hashMenus['/' + hashKey] = obj;
                if (Array.isArray(key.menus)) {
                    setMenu2Hash(key.menus, key.menuurl);
                }
            }
        });
    }
    setMenu2Hash(userInfo.menus);

    //允许的路径
    let allowedRouter = [];
    //遍历本地路由
    let findLocalRoute = function (array, base, pobj) {
        let replyResult = [];
        array.forEach(function (route) {
            let pathKey = (base ? base + '/' : '') + route.path;
            let obj = hashMenus[pathKey];
            if (obj || pathKey.indexOf('index') != -1) {
                if (Array.isArray(route.children)) {
                    route.children = findLocalRoute(route.children, route.path, obj);
                }
                if(obj)
                {
                    route.icon = obj.icon;
                    route.title = obj.title;
                }
                else
                {
                    route.icon = pobj.icon;
                    route.title = pobj.title;
                }
                replyResult.push(route);

            }
        });
        if (base) {
            return replyResult;
        } else {
            allowedRouter = allowedRouter.concat(replyResult);
        }
    }
    findLocalRoute(appRouter);
    return allowedRouter;
};
//3. 动态注入路由
const extendRoutes = allowedRouter => {
    //let originPath = Util.deepcopy(allowedRouter);
    router.addRoutes(allowedRouter.concat([{
        path: '*',
        redirect: '/404'
    }]));
};

//4. 保存菜单
const storageMenu = allowedRouter => {

    allowedRouter.forEach(route => {
        if (route.children) {
            if (!route.meta) route.meta = {};
            route.meta.children = route.children;
        }
    });
    store.state.app.menuList = allowedRouter;
}

//5. 初始化权限
const initPermission = resourcePermission => {

    //权限检查方法
    Vue.prototype.$_has = function (rArray) {
        let resources = [];
        let permission = true;
        if (Array.isArray(rArray)) {
            rArray.forEach(function (e) {
                resources = resources.concat(e.p);
            });
        } else {
            resources = resources.concat(rArray.p);
        }
        resources.forEach(function (p) {
            if (!resourcePermission[p]) {
                return permission = false;
            }
        });
        return permission;
    }
};

router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);
    //1. 判断当前是否锁定状态
    if (Cookies.get('locking') === '1' && to.name !== 'locking') {
        next({
            replace: true,
            name: 'locking'
        });
    } else if (Cookies.get('locking') === '0' && to.name === 'locking') {
        next(false);
    } else {

        if (!Cookies.get('user') && to.name !== 'login') {  // 判断是否已经登录且前往的页面不是登录页
            next({
                name: 'login'
            });
        } else if (Cookies.get('user') && to.name === 'login') { // 判断是否已经登录且前往的是登录页
            Util.title();
            next({
                name: 'home_index'
            });
        }
        if(Cookies.get('user'))
        {
            let refresh = store.state.app.refresh;
            //如果第一次进来，查询权限
            if(refresh)
            {
                //获取用户权限资源
                requestPermission({}).then(res => {
                    var data = res.data;
                    if (data.result) {

                        if(data.data == "")
                        {
                            next(to.path);
                            return;
                        }
                        //获得允许访问路由
                        let allowedRouter = getRoutes(data.data);
                        if (!allowedRouter || !allowedRouter.length) {
                            return document.body.innerHTML = ('<h1>账号访问受限，请联系系统管理员！</h1>');
                        }
                        // 动态注入路由
                        extendRoutes(allowedRouter);
                        //保存菜单数据
                        storageMenu(allowedRouter);
                        //初始化权限
                        initPermission(data.data.permission);

                        store.state.app.refresh = false;

                        next(to.path); //replace: true 不记录历史
                    }
                    else
                    {
                        iView.Notice.error({
                            title: '提示',
                            desc: data.msg
                        });
                    }
                });
            }
            else
                next();
        }
        else
            next();
    }
});

router.afterEach((to, from, next) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});


